package com.lc.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lc.constant.Constants;
import com.lc.pojo.PmsComment;
import com.lc.pojo.PmsCommentPic;
import com.lc.pojo.UmsUser;
import com.lc.pojo.dto.PmsCommentDto;
import com.lc.pojo.dto.PmsCommentPicDto;
import com.lc.pojo.param.PmsCommentParam;
import com.lc.result.Page;
import com.lc.result.Result;
import com.lc.result.ResultUtils;
import com.lc.service.PmsCommentPicService;
import com.lc.service.PmsCommentService;
import com.lc.service.UmsUserService;
import com.lc.utils.JWTUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 评价
 * @Author lc
 */

@RestController
@RequestMapping("/pms/comment")
public class PmsCommentController {

    @Resource
    private PmsCommentService pmsCommentService;

    @Resource
    private PmsCommentPicService pmsCommentPicService;

    @Resource
    private UmsUserService umsUserService;

    // 发表评价接口
    @PostMapping("/postComment")
    @Transactional
    public Result postComment(PmsCommentParam pmsCommentParam, HttpServletRequest request) {
        String token = request.getHeader(Constants.Redis.PREFIX_TOKEN);
        if (StringUtils.hasLength(token)) {
            // 获取当前登录用户
            UmsUser umsUser = JWTUtil.parseToken(token);
            if (umsUser != null) {
                PmsComment pmsComment = new PmsComment();

                // 商品spuID
                pmsComment.setSpuId(pmsCommentParam.getSpuId());
                // 用户ID
                pmsComment.setUserId(umsUser.getId());
                // 评价星数
                pmsComment.setStar(pmsCommentParam.getStar());
                // 评价内容
                pmsComment.setContent(pmsCommentParam.getContent());
                // 评价图片：0->无图；1->有图
                List<String> imgIds = pmsCommentParam.getImgIds();
                if (imgIds != null && !imgIds.isEmpty()) {
                    pmsComment.setIsPic((byte) 1);

                    // 商品评价图片添加
                    List<PmsCommentPic> commentPics = imgIds.stream()
                            .map(imgId -> {
                                PmsCommentPic commentPic = new PmsCommentPic();
                                commentPic.setCommentId(pmsComment.getId());
                                commentPic.setPicUrl(imgId);
                                return commentPic;
                            }).collect(Collectors.toList());
                    pmsCommentPicService.saveBatch(commentPics);

                } else {
                    pmsComment.setIsPic((byte) 0);
                }

                boolean save = pmsCommentService.save(pmsComment);
                if (save) {
                    return ResultUtils.returnSuccess();
                } else {
                    return ResultUtils.returnFail("评价失败");
                }
            } else {
                return ResultUtils.returnFail("获取当前登录用户失败");
            }
        } else {
            return ResultUtils.returnFail("评价前，请登录");
        }
    }

    //查询评价列表接口
    @GetMapping("/commentList")
    public Result commentList(@RequestParam Integer spuId,
                              @RequestParam(defaultValue = "-1") Integer isPic,
                              @RequestParam(defaultValue = "1") Integer pageNo,
                              @RequestParam(defaultValue = "20") Integer pageSize) {

        // 查询评价集
        LambdaQueryWrapper<PmsComment> wrapperPC = new LambdaQueryWrapper<>();
        wrapperPC.eq(PmsComment::getSpuId, spuId)
                .eq(isPic == 1,PmsComment::getIsPic, isPic)
                .orderByDesc(PmsComment::getCreatedTime);
        List<PmsComment> listPC = pmsCommentService.list(wrapperPC);

        // 查询评价图片列表
        List<PmsCommentPic> listPCP;
        if (!listPC.isEmpty()) {
            List<Long> commentIds = listPC.stream().map(PmsComment::getId).collect(Collectors.toList());
            LambdaQueryWrapper<PmsCommentPic> wrapperPCP = new LambdaQueryWrapper<>();
            wrapperPCP.in(PmsCommentPic::getCommentId, commentIds);
            listPCP = pmsCommentPicService.list(wrapperPCP);
        } else {
            listPCP = Collections.emptyList();
        }

        // 转换为DTO对象列表
        List<PmsCommentDto> listPCDto = listPC.stream().map(pc -> {
            PmsCommentDto pmsCommentDto = new PmsCommentDto();
            BeanUtils.copyProperties(pc, pmsCommentDto);
            pmsCommentDto.setCommentId(pc.getId());

            UmsUser umsUser = umsUserService.getById(pc.getUserId());
            pmsCommentDto.setUserName(umsUser.getUserName());
            pmsCommentDto.setAddTime(String.valueOf(pc.getCreatedTime()));

            List<PmsCommentPicDto> listPCPDto = listPCP.stream().filter(pcp -> pcp.getCommentId().equals(pc.getId()))
                    .map(pcp -> {
                        PmsCommentPicDto pmsCommentPicDto = new PmsCommentPicDto();
                        BeanUtils.copyProperties(pcp, pmsCommentPicDto);
                        return pmsCommentPicDto;
                    }).collect(Collectors.toList());

            pmsCommentDto.setImgList(listPCPDto);
            return pmsCommentDto;
        }).collect(Collectors.toList());

        Page<PmsCommentDto> page = new Page<>(listPCDto, pageNo, pageSize, listPCDto.size());

        return ResultUtils.returnDataSuccess(page);
    }

    }
